package csc.fresher.spring.controller;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import csc.fresher.spring.dao.UserDAOImpl;
import csc.fresher.spring.model.User;

@Controller
@RequestMapping("/register")
public class RegisterController {

	@Autowired
	private UserDAOImpl dao;

	@ModelAttribute("user")
	public User contructUser() {
		return new User();
	}

	@RequestMapping
	public String goRegister() {
		return "register";
	}

	@RequestMapping(value = "/registerform", method = RequestMethod.POST)
	public String Register(@Valid @ModelAttribute("user") User user,
			BindingResult rs, Model model) {
		if (rs.hasErrors()) {
			return "register";
		}
		BCryptPasswordEncoder encode = new BCryptPasswordEncoder();
		dao.insertUser(user.getUsername(), encode.encode(user.getPassword()),
				user.getIdcard(), user.getFirstname(), user.getLastname(),
				user.getPhone(), user.getEmail());
		dao.insertUserRole(user.getUsername());
		model.addAttribute("message", "Welcome " + user.getUsername());
		return "index";
	}
}
